<template>
	<view class="tabs">
		<view class="" >
		<!-- 房间 -->
		<view class="tabs-header" >
			<scroll-view :scroll-x="true" :show-scrollbar="false" class="tabs-handler scrollbar">
				<text :class="'tabs-item ' + (currentRoom.id === '' ? 'selected' : '')"
					@tap="onBindtapSelectRoom({id:''})">{{$t('General.home.all')}}</text>
				<template v-for="(item, index) in roomList">
					<text :key="item.id" :class="'tabs-item ' + (item.id === currentRoom.id ? 'selected' : '')"
						@tap="onBindtapSelectRoom(item)">{{ item.roomName }}</text>
				</template>
			</scroll-view>
			<uni-icons custom-prefix="iconfont" type="icon-gengduo2" size="24" @tap="onBindtapRoom"></uni-icons>
		</view>
		<!-- 设备 -->
		<scroll-view class="tabs-content"  :show-scrollbar="false"
		    :style="{height:windowHeight+'px'}"
			:scroll-y="true" :refresher-enabled="true" :refresher-triggered="triggered"
			@refresherpulling="bindrefresherpulling" @refresherrefresh="bindrefresherrefresh"
			@refresherrestore="bindrefresherrestore" @refresherabort="bindrefresherabort">
			<!-- 全部设备 或 某个房间的设备 -->
			<template v-for="(item, index) in newList">
				<view :key="item.deviceNo"
					v-if="currentRoom.id === '' ? true : item.roomId === currentRoom.id ? true : false" class="card"
					@longpress="onBindlongtapDevice(item)" @touchstart="onBindtouchstart" @touchend="onBindtouchend"
					@tap="onBindtapDevice(item)">
					<template v-if="item.devicePic">
						<image :src="item.devicePic" lazy-load style="width: 64rpx; height: 64rpx"></image>
					</template>
					<template v-else>
						<uni-icons custom-prefix="iconfont" type="icon-video-camera" size="32" color="#FF0025">
						</uni-icons>
					</template>
					<view v-if="!item.isVirtual"
						:class="'status ' + (item.status.status === 'online' ? (item.status.wakeUpStatus === '0' ?(item.status.wakeUpEnable === '0' ? 'deep' : 'dormancy'):item.status.wakeUpStatus === '2'?'sleeping' : 'online') : 'offline')">
						{{ item.status.status === 'online' ? (item.status.wakeUpStatus === '0' ? (item.status.wakeUpEnable === '0' ? $t('General.device.deep'):$t('General.device.sleep')):item.status.wakeUpStatus === '2'? $t('General.device.toSleep'): $t('General.device.online')) : $t('General.device.offLine') }}
					</view>
					<view v-else class="status virtual">Debug</view>
					<view class="rpsAbnormal" @click.stop="oninterEnable" v-if="item.interEnable">
						<image src="https://statics.xmcsrv.net/weixin/device/rpsAbnormal.png" style="width: 44rpx; height: 44rpx"></image>
					</view>
					<view>
						<view class="title ellipsis">{{ item.deviceName }}</view>
						<view class="u-f-sbc listFoot" style="height: 30rpx;margin-top: 10rpx;">
							<view class="tips ellipsis">{{ item.roomName }}</view>
							<!-- <image class="cloudIcon" v-for="(item2,index2) in item.cloudServiceIcon" :key="index2"
							style="margin-left: 5px;" :src="item2" mode="" /> -->
							<!-- <uni-icons v-if="item.xmcCssVid&&item.xmcCssVid.support" type="bottom" size="20"
								color="#999" @click.native.stop.prevent="showCloudStorge(item)"/> -->
						</view>
					</view>
				</view>
			</template>
			<view style="display: block;height: 24rpx;clear: both"></view>
			<!-- 获取单个设备分享的列表 -->
			<view style="display: block;">
				<template v-if="sharedDeviceList.length>0" >
					<text class="shareList" >我收到的共享设备</text>
					<view v-for="(item, index) in sharedDeviceList" :key="index">
						<view  :key="item.deviceNo"
							class="card"
							@longpress="onBindlongtapDevice(item,'sharedDevice')" @touchstart="onBindtouchstart" @touchend="onBindtouchend"
							@tap="onBindtapDevice(item)">
							<template v-if="item.devicePic">
								<image :src="item.devicePic" lazy-load style="width: 64rpx; height: 64rpx"></image>
							</template>
							<template v-else>
								<uni-icons custom-prefix="iconfont" type="icon-video-camera" size="32" color="#FF0025">
								</uni-icons>
							</template>
							<view v-if="!item.isVirtual"
								:class="'status ' + (item.status.status === 'online' ? (item.status.wakeUpStatus === '0' ?(item.status.wakeUpEnable === '0' ? 'deep' : 'dormancy'):item.status.wakeUpStatus === '2'?'sleeping' : 'online') : 'offline')">
								{{ item.status.status === 'online' ? (item.status.wakeUpStatus === '0' ? (item.status.wakeUpEnable === '0' ? '深度休眠':'休眠'):item.status.wakeUpStatus === '2'? '准备休眠中': '在线') : '离线' }}
							</view>
							<view v-else class="status virtual">Debug</view>
							<view>
								<view class="title ellipsis">{{ item.deviceName }}</view>
							</view>
						</view>
					</view>	
				</template>
			</view>
			<view style="display: block;height: 30rpx;clear: both"></view>
		</scroll-view>
		</view>
		<view class="" v-if="false">
			<j-device-preview @showCloudStorge="showCloudStorge" @onBindlongtapDevice="onBindlongtapDevice" :isTab="true" ref="expansionUi" :device='newList[0]' :showHeader="true"/>
		</view>
		<j-sheet ref="popupSheet" :list="sheetList" @click="cloudService"></j-sheet>
		<popup ref="popupMask" :device="maskInfo" @delete="onDelDevice" :list="maskList"/>
		<j-modal :value="abnormalModal" okText="帮助" cancelText="取消" title="提示" @cancel="cancelAbnormal" @ok="onJumpToHelp">
			<view slot="content" class="popupCont">
				<image src="https://statics.xmcsrv.net/weixin/device/wifiAbnormal.png" mode="widthFix" style="width: 60%;height: auto;"/>
				<view class="">
					设备访问外网异常,
				</view>
				<view class="">
					请检查路由器设置
				</view>
			</view>
		</j-modal>
	</view>
</template>

<script>
	import popup from './popup';
	const {
		showCloud,
		getStatus,
		deviceStorage
	} = require('@/utils/util.js');
	let constant = getApp().globalData.constant;
	let EE_DEV_SMARTDOORLOCK = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK;
	let EE_DEV_SMARTDOORLOCK2 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK2;
	let EE_DEV_SMARTDOORLOCK3 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK3;
	let EE_DEV_SMARTDOORLOCK4 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK4;
	let EE_DEV_SMARTDOORLOCK5 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK5;
	let EE_DEV_SMARTDOORLOCK6 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK6;
	let EE_DEV_SMARTDOORLOCK7 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK7;
	let EE_DEV_SMARTDOORLOCK8 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK8;
	let EE_DEV_SMARTDOORLOCK9 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK9;
	let EE_DEV_SMARTDOORLOCK10 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK10;
	let EE_DEV_SMARTDOORLOCK11 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK11;
	let EE_DEV_SMARTDOORLOCK12 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK12;
	let EE_DEV_SMARTDOORLOCK13 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK13;
	let EE_DEV_SMARTDOORLOCK14 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK14;
	let EE_DEV_SMARTDOORLOCK15 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK15;
	let EE_DEV_SMARTDOORLOCK16 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK16;
	let EE_DEV_SMARTDOORLOCK18 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK18;
	let EE_DEV_SMARTDOORLOCK21 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK21;
	
	export default {
		components: {
			popup
		},
		props: {
			isBack: false,
			deviceNo: '',
			sns:{
				type: Array,
				default: () => []
			},
		},
		data() {
			return {
				abnormalModal:false,//外网不通
				deviceList: [],// 设备列表
				roomList: [],//房间列表
				currentRoom: {
					id: '' //当前房间
				},
				triggered: true,// 下拉刷新状态
				tips: {
					text: ''
				},
				sheetList: [],
				serviceIconList:[],
				device: {
					deviceName: '',
					deviceNo: ''
				},
				currentGroupId: uni.getStorageSync('currentGroupId'),
				tapDevice: {},
				deviceTimer: null,
				deviceSecond: 15,
				maskList: [],
				maskInfo: {},
				newList:[],
				isConnect:false,
				currentTime:0,
				isShowStatusModal:false,
				deleteInfo:{
					userGroupName:'',
					sn:'',
					deviceName:'',
				},
				deletePopup:false,
				sharedDeviceList:[],
				retryCount: 0,
                isDeviceOnline: false,
                intervals: [ 10000, 15000], // 不同轮询时段的时间间隔
				windowHeight:0,
			};
		},
		destroyed() {
			clearTimeout(this.deviceTimer)
		},
		beforeMount() {
			console.log('啊？？？')
			let sys = uni.getSystemInfoSync();
			this.windowHeight = sys.windowHeight-90
			console.log(sys,'sys')
			// 在组件实例进入页面节点树时执行
			this.initData()
		},
		onPageShow() {
			uni.showTabBar()
            uni.$on('updateDevicePosition', (data) => {
                this.updateDevicePosition(data)
            })
			// 更新设备信息
			uni.$on('editDeviceName',(data)=>{
				this.editDevice(data)
			})
			// 更新设备房间名称
			uni.$on('moveRoom',(data)=>{
				this.initData()
			})
			setTimeout(()=>{
				if(!this.isBack){
					this.initData()
				}
			},150)
			if(this.$refs.expansionUi && this.newList.length>0){
				if(this.newList[0].localUiKey == 'ui_doorlock_home' && this.newList.length == 1){
					setTimeout(()=>{
						this.$refs.expansionUi.getClineHeight()
					},200)
				}
			}
			//外网不通
			let interEnable = uni.getStorageSync('interEnable')
			let sns = uni.getStorageSync('interSns')
			if(interEnable && sns.length>0){
				setTimeout(()=>{
					uni.removeStorageSync('interEnable')
					this.pollDeviceStatus(sns) 
				}, 5000);
			}
			
			// if(uni.getStorageSync('appIsShow')){
			// 	this.initData()
			// 	uni.setStorageSync('appIsShow',false)
			// }
		},
		watch: {
			isBack(val) {
				if (val) {
					console.log('isback====',val);
					this.deviceSecond = 15
					let flag = false
					this.deviceList.forEach((item) => {
						if (item.deviceNo == this.deviceNo) {
							if(item.localUiKey !='ui_doorlock_home'){
								item.status.wakeUpStatus = '2'
								flag = true
							}
						}
					})
					if (flag) {
						this.deviceTimer = setTimeout(() => {
							this.getRoomListByPage();
							clearTimeout(this.deviceTimer)
						}, 15000)
					}
				}
			}
		},
		methods: {
			oninterEnable(){
				this.abnormalModal = true;	
			},
			pollDeviceStatus(sns) {
				if (this.retryCount > 3 || this.isDeviceOnline) {
					// 如果达到最大重试次数或设备已在线，停止轮询
					return;
				}
				const interval = this.intervals[this.retryCount]; // 根据重试次数获取对应的间隔时间
				// 同步查询设备状态
				this.getDeviceToken(sns,'inter');
				if (this.isDeviceOnline) {
					console.log('设备已在线');
				} else {
					this.retryCount++;
					setTimeout(()=>{
						this.pollDeviceStatus(sns)
					}, interval); 
				}
			},
			cancelAbnormal(){
				this.abnormalModal = false
			},
			onJumpToHelp(){
				uni.navigateTo({
					url: '/jvss/pagesMine/help/help'
				});
				this.cancelAbnormal()
			},
			initData(){
				let currentGroupId = uni.getStorageSync('currentGroupId')
				if(currentGroupId){
					this.getRoomListByPage();
				}
				this.getSharedDeviceList()
			},
            // 更新设备位置
            updateDevicePosition(data) {
                this.newList = [...data]
            },
			// 更新修改设备名称
			editDevice(data){
				this.newList.forEach((item,index)=>{
					if(data.sn == item.deviceNo){
						item.deviceName = data.deviceName
					}
				})
			},
			// mqtt消息
			websocketInfo(res) {
				let info = JSON.parse(res)
				if(info){
					this.deviceList.forEach((newItem)=>{
						if(newItem.deviceNo == info.sn){
							let status  = ''
							let doorLockInfo  = {}
							info.props.forEach((item)=>{
								this.$logs({info:'首页websocket消息',sn:info.sn,propValue: item.propValue,itemStatus:newItem.status || '',})
								if(item.propCode ==  "wifiSignal"){
									newItem.wifiSignal = item.propValue
								}
								if(item.propCode ==  "deviceDel" || item.propCode == "deviceReset"){
									this.getRoomListByPage()
								}
								if(item.propCode ==  "sleepState"){
									status  = item.propValue
								}
								if(item.propCode ==  "doorLockCall"){
									doorLockInfo  = item.propValue
								}
							})
							const setDeviceStatus = (wakeUpEnable, wakeUpStatus, statusValue) => {
								let snsinfo = uni.getStorageSync(info.sn);
								if(snsinfo.interEnable && statusValue == 'online'){
									delete snsinfo.interEnable;
									delete newItem.interEnable;
									uni.setStorageSync(info.sn,snsinfo);
									this.removeInterSns(info.sn)
								}
							    if (newItem.status) {
							        newItem.status.wakeUpEnable = wakeUpEnable;
							        newItem.status.wakeUpStatus = wakeUpStatus;
							        newItem.status.status = statusValue;
							    } else {
							        let s = {
							            wakeUpEnable,
							            wakeUpStatus,
							            status: statusValue,
							        };
							        this.$set(newItem, 'status', s);
							        this.$logs({info: `首页设备状态${status}`, sn: info.sn, item: newItem, propValue: item.propValue});
							    }
							};
							switch (status) {
							    case 'DeepSleep':
							        setDeviceStatus('0', '0', 'online');
							        break;
							    case 'LightSleep':
							        setDeviceStatus('1', '0', 'online');
							        break;
							    case 'PreSleep':
							        setDeviceStatus('1', '2', 'online');
							        break;
							    case 'WakeUp':
							    case 'MasterControlPreSleep':
							        setDeviceStatus('1', '1', 'online');
							        break;
							    case 'OffLine':
								    // setDeviceStatus('1', '1', 'notfound');
								    setTimeout(()=>{
										console.log(newItem.deviceNo,getStatus(newItem.status),'状态')
								    	if(getStatus(newItem.status) == 'OffLine'){
								    		this.initData()
								    	}
								    },3000)
							        break;
							}
						}
					})
					// this.newList = this.deviceList
				}		
			},
			/** ================================ 用户组/房间 ==================================== */
			// 选择房间
			onBindtapSelectRoom(ev) {
				this.$emit('editEmptyFlag',0)
				this.currentRoom.id = ev.id
				// this.currentGroupId = ev.userGroupId
				this.getRoomListByPage();
				uni.$emit('chooseRoom',{roomId:ev.id})
			},
            
			// 切换房间tab组件接收事件 home调用
			onSwitchRooms(ev){
				this.getRoomListByPage();
				uni.$emit('chooseRoom',{roomId:ev.id})
			},
			
			// 分页查询房间列表
			// 传参true表示切换了用户组，需要重置currentRoom
			getRoomListByPage(type) {
				// console.log(1)
				const data = {
					userGroupId: uni.getStorageSync('currentGroupId'),
					page: 1,
					limit: 999
				};
				getApp().globalData.api.getRoomListByPage(data, (result) => {
					console.log('房间列表:', result, this.currentRoom);
					this.roomList = result.data;
					this.getDeviceListByPage(type);	// 查询全部设备
					uni.setStorageSync('defaultRoom', result.data[0])
				});
			},
			
			// 点击跳转房间管理
			onBindtapRoom(ev) {
				uni.navigateTo({
					url: `/jvss/pagesDevice/group/room/room-list/room-list?groupId=${uni.getStorageSync('currentGroupId')}` // url: `/jvss/pagesDevice/group/room/room-list/room-list?groupId=${getApp().globalData.currentGroupId}`
				});
			},
			
			/** ================================ 设备 ==================================== */
			//根据设备状态排序
			sortDevice(){
				const statusOrder = ['online', 'offline', 'notfound']
				this.deviceList.sort(this.compareType)
				this.deviceList.sort((a, b) => {
					return statusOrder.indexOf(a.status.status) - statusOrder.indexOf(b.status.status)
				})
				this.deviceList.forEach((item,index)=>{
					let info = uni.getStorageSync(item.deviceNo);
					if(info.interEnable && info.status == 'online'){
						delete info.interEnable;
						delete item.interEnable;
						uni.setStorageSync(item.deviceNo,info);
						this.removeInterSns(item.deviceNo)
					}else{
						item.interEnable = info.interEnable
					}
				})
				this.newList = this.deviceList
			},
			//删除设备
			onDelDevice(e){
				console.log('监听删除设备',e);
				if(e && e.type == 'shareDevice'){
					//删除单个分享的设备
					this.getSharedDeviceList()
				}else{
					this.getDeviceListByPage()
				}
			},
			// 根据房间查询设备列表
			getDeviceListByPage(type) {
				const data = {
					userGroupId: uni.getStorageSync('currentGroupId'),
					page: 1,
					limit: 999,
				};
				getApp().globalData.api.getDeviceListByPage(data, (result) => {
					// console.log('某个房间的设备列表:', result);
					this.deviceList = result.data || []
					if(result.data.length == 0){
						uni.$emit('delDevice');
					}
					let sns = [];
					this.deviceList.forEach((item) => {
						if (item.deviceNo.includes('vir')) {
							this.$set(item, 'isVirtual', true)
						}
						sns.push(item.deviceNo)
						let cacheData = uni.getStorageSync(item.deviceNo)
						if(!cacheData.status){
							this.$set(item, 'status', {status:'notfound'})
						}else{
							let status = cacheData.status
							this.$set(item, 'status', status)
						}
					})
					if(this.currentRoom.id){
						let index = this.deviceList.findIndex(item=>item.roomId == this.currentRoom.id)
						this.$emit('editEmptyFlag',result.data.length == 0?1:index==-1?1:0)
					}else{
						this.$emit('editEmptyFlag',result.data.length == 0?1:0)
					}
					this.getDeviceListInfo();
					if(type == 'refresh'){
						this.$emit('sendWebsocketInfo',sns)
						// this.$parent.sendWebsocketInfo(sns)
					}
				});
			},
			// 查询别人分享给当前用户的设备列表（当前用户已接收）
			getSharedDeviceList(){
				let data = {
					page:1,
					limit:999,
				}
				getApp().globalData.api.getSharedDeviceList(data, (result) => {
					console.log('查询别人分享给当前用户的设备列表',result);
					this.sharedDeviceList = result.data
					uni.$emit('getSharedDeviceList',result.data)
					let sns = []
					result.data.forEach((item)=>{
						sns.push(item.deviceNo)
						let cacheData = uni.getStorageSync(item.deviceNo)
						if(!cacheData.status){
							this.$set(item, 'status', {status:'notfound'})
						}else{
							let status = cacheData.status
							this.$set(item, 'status', status)
						}
					})
					if(result.data.length>0){
						this.getDeviceToken(sns,'shareList')
					}
				})
			},
			// 查询设备信息
			getDeviceListInfo() {
				let sns = [];
				this.deviceList.forEach((item) => {
					sns.push(item.deviceNo);
				});
				if (sns.length > 0) {
					this.getDeviceToken(sns);
				} else {
					this.newList = []
					uni.setStorageSync('bossDeviceList', [])
				}
			},
			// 获取设备token
			getDeviceToken(sns,type) {
				const data = {
					sns: sns
				};
				getApp().globalData.api.getDeviceToken(data, (result) => {
					// console.log('获取设备token:', result);
					let tempList = type == 'shareList'?this.sharedDeviceList:this.deviceList
					tempList.forEach((item) => {
						result.forEach((pro) => {
							if (item.deviceNo === pro.sn) {
								item.token = pro.token;
								// this.$set(item,'status',{status:'online',wakeUpEnable:'1',wakeUpStatus:'0'})
							}
						});
					});
					let tokenList = [];
					result.forEach((item) => {
						tokenList.push(item.token);
					});
					this.sortDevice()
					this.getDeviceStatus(tokenList, tempList,type);
				});
			},
			// 获取设备状态
			getDeviceStatus(tokenList, deviceList,type) {
				const data = {
					otherStatus:true,
					token: tokenList
				};
				//  getDeviceStatus  getNewDeviceStatus
				getApp().globalData.api.getDeviceStatus(data, (result) => {
					uni.stopPullDownRefresh()
					let sns = [];
					let tempList = type == 'shareList'?this.sharedDeviceList:this.deviceList
					result.forEach((pro) => {
						let cacheData = uni.getStorageSync(pro.uuid)
						if(!cacheData){
							uni.setStorageSync(pro.uuid,{status:pro})
						}else{
							cacheData['status'] = pro
							uni.setStorageSync(pro.uuid,cacheData)
						}
					});
					tempList.forEach((item) => {
						sns.push(item.deviceNo);
						result.forEach((pro) => {
							if (item.deviceNo === pro.uuid) {
								this.$set(item, 'status', pro)
							}
						});
					});
					//外网不通
					if (type == 'inter') {
						tempList.forEach((item) => {
							result.forEach((pro) => {
								if (item.deviceNo === pro.uuid) {
									if (pro.status === 'notfound' &&
										pro.rps === 'notfound' &&
										!pro.wakeUpEnable &&
										!pro.wakeUpStatus) {
										this.interforenable = false;
										if (this.retryCount >= 3 && !this.interforenable) {
											item.interEnable = true;
											deviceStorage(item.deviceNo, 'interEnable', true)
										}
									} else {
										this.interforenable = true;
										this.isDeviceOnline = true;
										this.removeInterSns(item.deviceNo)
									}
								}
							});
						});
					}
					if(type == 'shareList'){
						this.sharedDeviceList = tempList
					}else{
						this.deviceList = tempList || []
						this.sortDevice()
						this.deviceList.forEach((item) => {
							if (!item.deviceNo.includes('vir')) {
								const data = {
									sn: item.deviceNo,
									caps: ['xmc.css', 'xmc.voes', 'pms.voes', 'pms.sms', 'net.cellular']
								};
								getApp().globalData.api.reqCaps(data, (result) => {
									let caps = result.caps;
									let time = Math.floor(new Date().getTime() / 1000);
									this.$set(item, 'xmcCssVid', {
										support: caps['xmc.css.vid.support'],
										enable: caps['xmc.css.vid.enable'],
										expirate: caps['xmc.css.vid.expirationtime'],
										isExpire: caps['xmc.css.vid.expirationtime'] < time ? false : true
									}) //云存储
									this.$set(item, 'xmcVoes', {
										support: caps['xmc.voes.support'],
										enable: caps['xmc.voes.enable'],
										expirate: caps['xmc.voes.expirationtime'],
										isExpire: caps['xmc.voes.expirationtime'] < time ? false : true
									}) //云电话
									this.$set(item, 'pmsVoes', {
										support: caps['pms.voes.support'],
										enable: caps['pms.voes.enable'],
										expirate: caps['pms.voes.expirationtime'],
										isExpire: caps['pms.voes.expirationtime'] < time ? false : true
									}) //语音报警
									this.$set(item, 'pmsSms', {
										support: caps['pms.sms.support'],
										enable: caps['pms.sms.enable'],
										expirate: caps['pms.sms.expirationtime'],
										isExpire: caps['pms.sms.expirationtime'] < time ? false : true
									}) //短信报警
									this.$set(item, 'netCellular', {
										support: caps['net.cellular.support'],
										enable: caps['net.cellular.enable'],
										expirate: caps['net.cellular.expirationtime'],
										isExpire: caps['net.cellular.expirationtime'] < time ? false : true
									}) //4G流量
									this.$set(item,'cloudServiceIcon',showCloud(item))
								})
							}
						})
						uni.setStorageSync('bossDeviceList', this.deviceList)
						this.newList = this.deviceList
					}
				});
			},
			removeInterSns(sn){
				let sns = uni.getStorageSync('interSns')
				sns = sns.filter(item => item !== sn);
				uni.setStorageSync('interSns',sns)
			},
			compareType(a, b) {
				if (a.parentPid == b.parentPid) {
					if (a.deviceNo > b.deviceNo) {
						return -1
					} else if (a.deviceNo < b.deviceNo) {
						return 1
					} else {
						return 0
					}
				} else {
					return a.parentPid > b.parentPid ? -1 : 1
				}
			},
			compareType1(property) {
				const collator = new Intl.Collator('en');
				return function(a, b) {
					var value1 = a[property];
					var value2 = b[property];
					return collator.compare(value2, value1);
				}
			},
			//显示云服务弹框
			showCloudStorge(item) {
				this.tapDevice = item
				let list = ['云存储', '云电话', '语音报警', '短信报警', '4G流量']
				let icon = ['https://statics.xmcsrv.net/weixin/cloud/icon/xmcCss.png',
					'https://statics.xmcsrv.net/weixin/cloud/icon/xmcVoes.png',
					'https://statics.xmcsrv.net/weixin/cloud/icon/pmsVoes.png',
					'https://statics.xmcsrv.net/weixin/cloud/icon/pmsSms.png',
					'https://statics.xmcsrv.net/weixin/cloud/icon/netCellular.png'
				]
				this.sheetList = []
				const types = ['xmcCssVid', 'xmcVoes', 'pmsVoes', 'pmsSms', 'netCellular'];
				const generateSheetItem = (item, type, name, iconUrl) => {
				    let time = Math.floor(new Date().getTime() / 1000);
					const typeMap = {
					        'xmcCssVid': 'xmc.css',
					        'xmcVoes': 'xmc.voes',
					        'pmsVoes': 'pms.voes',
					        'pmsSms': 'pms.sms',
					        'netCellular': 'net.cellular'
					    };
				    if (item[type].support) {
				        let isExpire = item[type].expirate < time ? false : true;
				        return {
				            url: iconUrl,
				            classifyId: typeMap[type],
				            name: name,
				            isExpire: isExpire,
				            ...item[type]
				        };
				    }
				    return null;
				}
				for (let i = 0; i < types.length; i++) {
				    const sheetItem = generateSheetItem(item, types[i], list[i], icon[i]);
				    if (sheetItem) {
				        this.sheetList.push(sheetItem);
				    }
				}
				console.log('sheetList', this.sheetList);
				uni.hideTabBar();
				this.$refs.popupSheet.open();  
			},
			// 云服务弹框点击事件
			cloudService(e) {
				console.log('e', e);
				if (e.isExpire) {
					if (e.classifyId == 'xmc.css') {
						uni.navigateTo({
							url: '/jvss/pagesDevice/device/device-live/door-lock/msgDetail?device=' + encodeURIComponent(JSON.stringify(this.tapDevice))
							// url:'/jvss/pagesDevice/device/device-live/replay/replay?device='+JSON.stringify(this.tapDevice)
						})
					} else {
						const {adminToken,devicePic,deviceName,devPassWord,roomId,deviceNo,devUserName,userGroupId} = this.tapDevice
						this.$routing(`${this.$pages["record"]}?sn=${deviceNo}&type=${'voes'}&devName=${deviceName}&u=${devUserName}&p=${devPassWord}&adminToken=${adminToken}&userGroupId=${userGroupId}&roomId=${roomId}&devIcon=${devicePic}&alarmEnable=false`)
						// uni.navigateTo({
						// 	url: '/jvss/pageCloud/buy/default?classifyId=' + e.classifyId + '&sn=' + this.tapDevice
						// 		.deviceNo
						// })
					}
				} else {
					uni.navigateTo({
						url: '/jvss/pageCloud/buy/default?classifyId=' + e.classifyId + '&sn=' + this.tapDevice
							.deviceNo
					})
				}
				this.$refs.popupSheet.close()
			},
			// 点击设备
			onBindtouchstart(ev) {
				this.startTime = ev.timeStamp;
			},
			onBindtouchend(ev) {
				this.endTime = ev.timeStamp;
			},
			onBindtapDevice(ev) {
				console.log('跳转设备:', ev);
				// #ifdef MP-WEIXIN
				this.$logs({info:'点击设备时间',sn:ev.deviceNo})
				// #endif
				let device = ev
				if (ev.deviceNo.includes('vir')) {
					uni.navigateTo({
						url: `/jvss/pages/h5/h5?device=${encodeURIComponent(JSON.stringify(device))}`
					});
					return
				}
				if (this.endTime - this.startTime < 350) {
					if (device.status.status === 'online') {
						if(device.localUiKey != 'ui_doorlock_home'){
							if (device.status.wakeUpStatus == 2) {
								return uni.showToast({
									title: '让我先休眠一下，稍后唤醒我',
									icon: 'none'
								})
							}
						}
						// if (device.pid === EE_DEV_SMARTDOORLOCK3 || device.pid === EE_DEV_SMARTDOORLOCK8) {
						// 	this.onJumpToBock(device)
						// }else{
							this.onJumpToGeneral(device)
						// }
					} else {
						if (device.deviceNo.includes('vir')) {
							uni.navigateTo({
								url: `/jvss/pages/h5/h5?device=${encodeURIComponent(JSON.stringify(device))}`
							});
							return
						}
						// if (device.localUiKey == 'ui_doorlock_home') {
						// 	uni.navigateTo({
						// 		url : `/jvss/pagesDevice/device/device-live/door-lock/doorLockHome?device=${encodeURIComponent(JSON.stringify(device))}`
						// 	});
						// 	return
						// }
						uni.showToast({
							title: this.$t('General.add.offline'),
							icon: 'none'
						});
					}
				}
			},
			// 跳转到通用设备
            onJumpToGeneral(device) {
                if (device.status.wakeUpStatus == 0 && device.status.wakeUpEnable == 0 && device.localUiKey != 'ui_doorlock_home') {
                    uni.showToast({
                        title: '设备处于深度睡眠需要手动唤醒',
                        icon: 'none'
                    })
                    return
                }
				url= `/jvss/pagesDevice/device/device-live/door-lock/live-h5-test?device=${encodeURIComponent(JSON.stringify(device))}`
				uni.navigateTo({
					  url: url
				});
				return
				let url = `/jvss/pagesDevice/device/device-live/live/live?device=${encodeURIComponent(JSON.stringify(device))}`		
						// uni.navigateTo({
						// 	url: url
						// });
						// return
				if (device.uiUrl) {
					url= `/jvss/pages/h5/h5?device=${encodeURIComponent(JSON.stringify(device))}`
				} 
				else if (device.localUiKey == 'ui_doorlock_home') {
						//乐鑫门锁或门铃
						url = `/jvss/pagesDevice/device/device-live/door-lock/doorLockHome?device=${encodeURIComponent(JSON.stringify(device))}`
				} else if (device.localUiKey == 'ui_doorlock') {
					if (device.parentPid === EE_DEV_SMARTDOORLOCK7 || device.parentPid === EE_DEV_SMARTDOORLOCK12 || device.parentPid === EE_DEV_SMARTDOORLOCK21) {
						//乐鑫门锁或门铃
						url =
						`/jvss/pagesDevice/device/device-live/door-lock/live-lexin?device=${encodeURIComponent(JSON.stringify(device))}`
							// `/jvss/pagesDevice/device/device-live/door-lock/doorLockHome?device=${encodeURIComponent(JSON.stringify(device))}`
					}else{
						url = `/jvss/pagesDevice/device/device-live/door-lock/live?device=${encodeURIComponent(JSON.stringify(device))}`
					}
				}else if (device.pid === constant.DEVICE_TYPE.EE_DEV_FEEDER) {
                    // 喂食器
                } else if (device.pid === constant.DEVICE_TYPE.EE_DEV_IDR ||
                    device.pid === constant.DEVICE_TYPE.EE_DEV_PEEPHOLE ||
                    device.pid == 285409282) {
                    // 门铃
					url= `/jvss/pagesDevice/device/device-live/live/live?device=${encodeURIComponent(JSON.stringify(device))}`
                } else if (
                    device.pid === EE_DEV_SMARTDOORLOCK2 ||
                    device.pid === EE_DEV_SMARTDOORLOCK4 ||
                    device.pid === EE_DEV_SMARTDOORLOCK5 ||
                    device.pid === EE_DEV_SMARTDOORLOCK6 ||
                    device.pid === EE_DEV_SMARTDOORLOCK7 ||
                    device.pid === EE_DEV_SMARTDOORLOCK9 ||
                    device.pid === EE_DEV_SMARTDOORLOCK10 ||
                    device.pid === EE_DEV_SMARTDOORLOCK11) {
                    // 通用门锁
					 url= `/jvss/pagesDevice/device/device-live/door-lock/live1?device=${encodeURIComponent(JSON.stringify(device))}`
                } else if (device.pid === EE_DEV_SMARTDOORLOCK) {
				    // 通用门锁
					 url= `/jvss/pagesDevice/device/device-live/door-lock/live?device=${encodeURIComponent(JSON.stringify(device))}`
				} else  {
                    console.log('深度休眠')
                    if (device.status.wakeUpStatus == 0 && device.status.wakeUpEnable == 0) {
                        uni.showToast({
                            title: '设备处于深度睡眠需要手动唤醒',
                            icon: 'none'
                        })
                        return
                    }
					url= `/jvss/pagesDevice/device/device-live/live/live?device=${encodeURIComponent(JSON.stringify(device))}`
                }
				uni.navigateTo({
					url: url
				});
            },
            //博客定制主动查看
            onJumpToBock(device) {
                if (device.status.wakeUpStatus == 1) {
                    uni.navigateTo({
                        url: `/jvss/pagesDevice/device/device-live/door-lock/live1?device=${encodeURIComponent(JSON.stringify(device))}`
                    });
                    return
                }
                this.getTailoredConfig(device, 'tap')
            },
			//关闭弹框
			closePopup() {
				this.$refs.popup.close()
			},
			// 长按设备
			onBindlongtapDevice(ev,type) {
				console.log('长按设备:', ev,type);
				let itemList = []
				if(type == 'sharedDevice'){
					itemList = [
                    //     {
					// 	title: this.$t('General.device.copy'),
					// 	subTitle: '',
					// 	type: "copy",
					// 	status: true
					// },
                        {
						title: this.$t('General.device.removeShare'),
						subTitle: '',
						type: "removeShare",
						status: true
					}]
				}else{
					itemList = [{
						title: this.$t('General.device.cloud'),
						subTitle: '',
						type: "cloud",
						status: false
					}, {
						// title: '设备设置',
						title: this.$t('General.device.setting'),
						subTitle: '',
						type: "set",
						// path: ev.localUiKey == "ui_doorlock_home" ? '/jvss/pagesDevice/device/device-live/door-lock/setting/setting-lexin' : "",
						// status: ev.localUiKey == "ui_doorlock_home"?true:false
						path: type == "ui_doorlock_home" ? '/jvss/pagesDevice/device/device-live/door-lock/setting/setting-lexin' : "",
						status: type == "ui_doorlock_home" ? true : false
					}, {
						title: this.$t('General.device.move'),
						subTitle: '',
						type: "room",
						status: true
					},
                    //     {
					// 	title: this.$t('General.device.copy'),
					// 	subTitle: '',
					// 	type: "copy",
					// 	status: true
					// },
                        {
						title: this.$t('General.device.share'),
						subTitle: '',
						type: "share",
						status: false
					}, {
						title: this.$t('General.device.delete'),
						subTitle: '',
						type: "delete",
						status: true
					}, ]
                    const appletIdentify = getApp().globalData.appletIdentify
                    const generalIdentify = getApp().globalData.generalIdentify
					if(ev.parentPid == EE_DEV_SMARTDOORLOCK7 || ev.localUiKey == 'ui_doorlock_home'){
                        if(!(appletIdentify===generalIdentify))
						itemList.unshift({
							title: '临时密码',
							subTitle: '',
							type: "pass",
							status: true
						})
					}
					this.$refs.popupMask.onBindtapAddUser();
					this.$refs.popupMask.shareSingleDevice(ev);
				}
				this.maskList = itemList;
				this.maskInfo = ev
				uni.hideTabBar()
				this.$refs.popupMask.open();
				if (ev.pid == EE_DEV_SMARTDOORLOCK3 || ev.pid === EE_DEV_SMARTDOORLOCK8) {
					this.getTailoredConfig(ev, 'longtap');
				}
			},
			// 获取电量协议接口
			getTailoredConfig(ev, type) {
				// uni.navigateTo({
				// 	url: `/jvss/pagesDevice/device/device-live/door-lock/live1?device=${encodeURIComponent(JSON.stringify(ev))}`
				// });
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				let token = ev.token
				let data = {
					"sn": ev.deviceNo,
					"configs": []
				};
				getApp().globalData.api.getTailoredConfig(data, token, (result) => {
					uni.hideLoading();
						// #ifdef MP-WEIXIN
					this.$logs({info:'获取设备主动查看状态',data:data,result:result})
					// #endif
					console.log(result['Consumer.SwitchWifiMode'], '主动查看')
					let switchwifimode = result['Consumer.SwitchWifiMode'] || {};
					if (Object.keys(switchwifimode).length>0) {
						if (type == 'tap') {
							if (switchwifimode.WifiMode == 1) {
								uni.showModal({
									title: '提示',
									content: '主动查看已关闭，请唤醒门锁',
									confirmText: '确定',
									showCancel: false,
									success: (res) => {
										if (res.confirm) {
											uni.showTabBar()
											this.$refs.popupMask.close();
										}
									}
								})
							} else if (switchwifimode.WifiMode == 0) {
								if (ev.status.wakeUpStatus == 0 && ev.status.wakeUpEnable == 0) {
                                    uni.showToast({
                                        title: '设备处于深度睡眠需要手动唤醒',
                                        icon: 'none'
                                    })
                                    return
                                }
								uni.navigateTo({
									url: `/jvss/pagesDevice/device/device-live/door-lock/live1?device=${encodeURIComponent(JSON.stringify(ev))}`
								});
							}
						} else {
							this.maskList.unshift({
								title: '主动查看',
								subTitle: '',
								type: "active",
								status: ev.pid == EE_DEV_SMARTDOORLOCK3 || ev.pid == EE_DEV_SMARTDOORLOCK8 ? true : false
							}, )
						}
					}else{
						console.log('ddddddddddddd===',switchwifimode);
						if (type == 'longtap') {
							switchwifimode['WifiMode'] = 0
							this.maskList.unshift({
								title: '主动查看',
								subTitle: '',
								type: "active",
								status: ev.pid == EE_DEV_SMARTDOORLOCK3 || ev.pid == EE_DEV_SMARTDOORLOCK8 ? true : false
							}, )
						}else{
							if (ev.status.wakeUpStatus == 0 && ev.status.wakeUpEnable == 0) {
							    uni.showToast({
							        title: '设备处于深度睡眠需要手动唤醒',
							        icon: 'none'
							    })
							    return
							}
							uni.navigateTo({
								url: `/jvss/pagesDevice/device/device-live/door-lock/live1?device=${encodeURIComponent(JSON.stringify(ev))}`
							});
						}
					}
					this.maskList.forEach(item => {
						if (item.type == "active") {
							item.subTitle = switchwifimode.WifiMode == 0 ? '已开启' : '未开启'
						}
					})
				});
			},
			//邀请
			onBindtapAddUser() {
				const data = {
					userGroupId: uni.getStorageSync('currentGroupId')
				}
				getApp().globalData.api.getKey(data, result => {
					console.log(result);
					wx.showModal({
						title: '邀请码',
						content: result,
						confirmText: '复制',
						showCancel: false,
						success(res) {
							if (res.confirm) {
								console.log('用户点击确定')
								wx.setClipboardData({
									data: result,
									success(res) {
										console.log(res);
									}
								})
							}
						}
					})
				})
			},

			// 删除设备
			delDevice(deviceNo) {
				let deviceList = uni.getStorageSync('deviceList');
				if (deviceList) {
					deviceList = deviceList.filter(item => item.deviceNo !== this.device.deviceNo); //删除对应序列号的缓存数据
				}
				console.log(deviceList);
				uni.showModal({
					title: '提示',
					content: '确认删除此设备？',
					success: (response) => {
						if (response.confirm) {
							const data = {
								deviceNo: deviceNo,
								clearNss:false
							};
							getApp().globalData.api.delDevice(data, (result) => {
								if (deviceList) {
									uni.setStorageSync('deviceList', deviceList);
								}
								uni.showToast({
									title: '成功删除！',
									success: () => {
										this.getDeviceListByPage(this.currentRoom.id);
									}
								});
							});
						}
					}
				});
			},

			/** ====================================下拉刷新============================================ */
			bindrefresherpulling(ev) {
				// console.log('被下拉',ev);
			},
            // 下拉刷新
			bindrefresherrefresh(ev) {
				// console.log('被触发',ev,this.triggered,'this.triggered');
				this.getRoomListByPage('refresh');
				setTimeout(() => {
					this.triggered = false
				}, 1000);
				this.getSharedDeviceList()
			},
			bindrefresherrestore(ev) {
				console.log('被复位', ev);
				setTimeout(() => {
					this.triggered = true
					this.triggered = 'restore'; // 需要重置
				}, 1100);
				// this.triggered = true
				console.log(getApp().globalData.keepTimer,'getApp().globalData.keepTimer')
				if(getApp().globalData.keepTimer){
					clearInterval(getApp().globalData.keepTimer);
					getApp().globalData.keepTimer = null
				}
				uni.hideLoading()
			},

			bindrefresherabort(ev) {
				console.log('被中止', ev);
			}
		}
	};
</script>
<style lang="scss">
	page {
		overflow: hidden;
	}
	.cloudIcon  {
		width: 35rpx;
		height: 35rpx;
	}
	.listFoot{
		justify-content: start;
		align-items: center;
	}
	::-webkit-scrollbar {
		display: none; //设置隐藏
		width: 0 !important; //设置大小
		height: 0 !important; //设置大小
		-webkit-appearance: none;
		background: transparent;
	}

	.tabs {
		width: auto;
	}

	.tabs-header {
		height: 80rpx;
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		align-items: center;
	}

	.tabs-handler {
		line-height: 72rpx;
		color: #88878c;
		white-space: nowrap;
		width: calc(100vw - 120rpx);
	}

	.tabs-handler .selected {
		color: #FF0025;
		font-weight: bold;
	}

	.tabs-item {
		padding-right: 36rpx;
	}

	.tabs-content {
		position: relative;
		// border: #FF0025 1px solid;
	}

	.card {
		position: relative;
		background: #ffffff;
		border-radius: 10rpx;
		width: calc(50% - 70rpx);
		float: left;
		display: inline;
		padding: 20rpx;
		margin: 20rpx 0 0 20rpx;
	}

	.status {
		position: absolute;
		top: 20rpx;
		right: 20rpx;
		font-size: 18rpx;
		line-height: 1;
		padding: 6rpx 12rpx;
		border-radius: 6rpx;
	}
    .rpsAbnormal{
		position: absolute;
		top: 70rpx;
		right: 30rpx;
    }
	.online {
		color: #ffffff;
		background: #FF0025;
	}

	.dormancy {
		color: #ffffff;
		background: #ee9002;
	}

	.deep {
		color: #ffffff;
		background: #80a7c8;
	}

	.offline {
		color: #666666;
		background: #eeeeee;
	}

	.sleeping {
		color: #fff;
		background: #9370d8;
	}

	.virtual {
		color: white;
		background: red;
	}

	.title {
		font-size: 28rpx;
		font-weight: bold;
		margin: 60rpx 0 0 0;
		word-break: break-all;
	}

	.tips {
		color: #999999;
		font-size: 24rpx;
		word-break: break-all;
		height: 30rpx;
		line-height: 30rpx;
	}

	.p-content {
		display: flex;
		flex-direction: column;
		justify-content: center;
		padding-top: 10px;
	}

	.sheet {
		width: 100%;
		align-items: center;
		flex-direction: column;
		display: flex;
		border-bottom: 1rpx solid #EEEEEE;
		padding: 20rpx 0
	}

	.cancel {
		flex-direction: row;
		padding: 10px 15px;
		display: flex;
		justify-content: center;
	}
	.popupCont{
		font-size: 30rpx;
		text-align: center;
		color: #333;
		.bannerImg{
			width: 90%;
			height: auto;
		}
	}
	.j-modal-title{
		color: #464646;
		font-weight: bold;
	}
	.hint{
		font-size: 34rpx;
	}
	.delTips{
		color: #FF0025;
	}
	.shareList{
		color: #666666;
		position: relative;
		left: 20rpx;
		font-size: 24rpx;
		margin-left: 20rpx;
		margin-top: 20rpx;
		padding-top: 20rpx;
	}
</style>